// src/services/torrents.js - 种子管理服务

import { get, post, uploadFile } from './api';
import {
  getAllTorrents as localGetAllTorrents,
  getTorrentById as localGetTorrentById,
  getTorrentsByCategory as localGetTorrentsByCategory,
  searchTorrents as localSearchTorrents,
  addTorrent as localAddTorrent,
  downloadTorrent as localDownloadTorrent,

  likeTorrent as localLikeTorrent,
  hasUserLikedTorrent as localHasUserLikedTorrent
} from '../utils/localStorage';
import { formatFileSize } from '../utils/formatUtils';

/**
 * 将字节转换为人类可读的大小格式
 * @param {number} sizeInBytes - 字节大小
 * @returns {string} - 格式化后的大小字符串
 */
const formatSizeFromBytes = (sizeInBytes) => {
  const bytes = Number(sizeInBytes);
  if (!bytes || isNaN(bytes) || bytes <= 0) return '0 B';

  if (bytes >= 1024 * 1024 * 1024 * 1024) {
    return `${(bytes / (1024 * 1024 * 1024 * 1024)).toFixed(1)} TB`;
  } else if (bytes >= 1024 * 1024 * 1024) {
    return `${(bytes / (1024 * 1024 * 1024)).toFixed(1)} GB`;
  } else if (bytes >= 1024 * 1024) {
    return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
  } else if (bytes >= 1024) {
    return `${(bytes / 1024).toFixed(1)} KB`;
  } else {
    return `${bytes} B`;
  }
};

/**
 * 获取所有人上传的种子列表（来自OSS接口）
 * @returns {Promise} - 所有种子列表数据
 */
export const getAllUploadedTorrents = async (retryCount = 0) => {
  try {
    console.log(`🔄 第${retryCount + 1}次尝试获取OSS数据...`);

    // 添加超时设置
    const controller = new AbortController();
    const timeoutId = setTimeout(() => controller.abort(), 10000); // 10秒超时

    const response = await get('/oss/get_torrent');
    clearTimeout(timeoutId);

    console.log('📡 原始API响应:', response);
    console.log('📊 响应类型:', typeof response, '是否为数组:', Array.isArray(response));

    // 检查响应格式，可能是直接返回数组，也可能包装在data中
    let torrentsData = [];
    if (Array.isArray(response)) {
      // 直接返回数组
      torrentsData = response;
      console.log('✅ API直接返回数组格式，长度:', torrentsData.length);
    } else if (response && response.code === 200 && response.data) {
      // 包装格式 {code: 200, data: [...]}
      torrentsData = Array.isArray(response.data) ? response.data : [];
      console.log('✅ API返回包装格式，数据长度:', torrentsData.length);
    } else if (response && response.code === 200) {
      // 包装格式但data在根级别
      torrentsData = [];
      console.log('⚠️ API返回code=200但无数据数组');
    } else {
      throw new Error(response?.message || '获取种子列表失败');
    }

    console.log('🚀 OSS API 成功获取种子数据:', torrentsData.length, '个种子');

    return {
      success: true,
      data: {
        torrents: torrentsData,
        total: torrentsData.length,
        source: 'OSS_API'
      }
    };
  } catch (error) {
    console.error(`❌ OSS API第${retryCount + 1}次调用失败:`, error);

    // 检查是否需要重试（最多重试2次）
    if (retryCount < 2) {
      console.warn(`🔄 准备第${retryCount + 2}次重试...`);
      await new Promise(resolve => setTimeout(resolve, 1000 * (retryCount + 1))); // 递增延时
      return getAllUploadedTorrents(retryCount + 1);
    }

    // 检查错误类型，更严格的网络错误判断
    const isNetworkError = (
      error.name === 'AbortError' ||
      error.message.includes('Failed to fetch') ||
      error.message.includes('NetworkError') ||
      error.message.includes('请求超时') ||
      error.message.includes('网络错误') ||
      error.code === 'NETWORK_ERROR' ||
      !error.status  // 没有HTTP状态码通常是网络问题
    );

    console.log('🔍 错误分析:', {
      errorName: error.name,
      errorMessage: error.message,
      errorStatus: error.status,
      isNetworkError: isNetworkError
    });

    if (isNetworkError) {
      console.warn('🔄 确认为网络错误，回退到本地存储');
      const torrents = localGetAllTorrents();

      return {
        success: true,
        data: {
          torrents: torrents,
          total: torrents.length,
          isLocalFallback: true,
          source: 'LOCAL_STORAGE'
        }
      };
    } else {
      // 如果是其他错误（比如后端返回了错误但API可达），返回空数组而不是模拟数据
      console.warn('🚫 API错误但不回退到模拟数据，返回空结果');
      return {
        success: true,
        data: {
          torrents: [],
          total: 0,
          apiError: true,
          source: 'API_ERROR'
        }
      };
    }
  }
};

/**
 * 获取种子列表
 * @param {Object} params - 查询参数 (page, limit, sort, order)
 * @returns {Promise} - 种子列表数据
 */
export const getTorrents = async (params = {}) => {
  try {
    // 构建查询字符串
    const query = new URLSearchParams();
    if (params.page) query.append('page', params.page);
    if (params.limit) query.append('limit', params.limit);
    if (params.sort) query.append('sort', params.sort);
    if (params.order) query.append('order', params.order);

    const queryString = query.toString();
    const endpoint = queryString ? `/torrents?${queryString}` : '/torrents';

    const response = await get(endpoint);
    return response;
  } catch (error) {
    console.warn('获取种子列表API连接失败，使用本地存储:', error);

    // 从localStorage获取种子列表
    const torrents = localGetAllTorrents();

    // 简单的客户端分页
    const page = params.page || 1;
    const limit = params.limit || 20;
    const start = (page - 1) * limit;
    const end = start + limit;
    const paginatedTorrents = torrents.slice(start, end);

    return {
      success: true,
      data: {
        torrents: paginatedTorrents,
        pagination: {
          total: torrents.length,
          page: page,
          limit: limit,
          pages: Math.ceil(torrents.length / limit)
        }
      }
    };
  }
};

/**
 * 获取种子详情
 * @param {number|string} id - 种子ID
 * @returns {Promise} - 种子详情数据
 */
export const getTorrentDetail = async (id) => {
  try {
    // 由于后端没有实现单独的种子详情接口，先尝试从OSS数据中查找
    console.log('🔍 从OSS数据中查找种子详情, ID:', id);

    const allTorrentsResponse = await getAllUploadedTorrents();

    if (allTorrentsResponse.success) {
      const torrents = allTorrentsResponse.data.torrents || [];
      console.log('📦 从OSS获取到', torrents.length, '个种子');

      // 在OSS数据中查找匹配的种子
      const foundTorrent = torrents.find(torrent => {
        // 支持多种ID匹配方式：id、hash、name等
        return torrent.id == id ||
          torrent.hash == id ||
          torrent.name == id ||
          String(torrent.id) === String(id) ||
          String(torrent.hash) === String(id);
      });

      if (foundTorrent) {
        console.log('✅ 在OSS数据中找到种子:', foundTorrent.name);

        // 适配数据格式为TorrentDetail页面期望的格式
        const adaptedTorrent = {
          id: foundTorrent.id || id,
          title: foundTorrent.name || foundTorrent.title || '未命名种子',
          category: foundTorrent.classification || '未分类', // 用于显示的分类
          classification: foundTorrent.classification || '未分类', // 保留原始字段用于筛选
          uploader: foundTorrent.uploader || '匿名用户',
          size: formatFileSize(foundTorrent.size || 0),
          sizeInBytes: foundTorrent.size || 0,
          uploadDate: foundTorrent.fileTimestamps || foundTorrent.uploadDate,
          seeders: foundTorrent.seeder || 0,
          leechers: 0, // OSS数据中没有leechers字段
          downloads: foundTorrent.download || 0,
          likes: foundTorrent.upvote || 0,
          views: foundTorrent.watchs || 0, // 新增：浏览量字段
          // 处理促销类型：后端category字段表示促销类型，null表示无促销
          promotion: foundTorrent.category && foundTorrent.category !== null ? foundTorrent.category : 'none',
          description: foundTorrent.comment || '暂无描述',
          coverImage: foundTorrent.presource || foundTorrent.pResource || 'https://via.placeholder.com/300x450',
          torrentUrl: foundTorrent.tresource || foundTorrent.tResource || null,
          hash: foundTorrent.hash || null,
          tags: [], // OSS数据中没有tags字段
          files: [], // OSS数据中没有files字段  

        };

        return {
          success: true,
          data: {
            torrent: adaptedTorrent
          }
        };
      }

      console.log('❌ 在OSS数据中未找到种子, ID:', id);
    }

    // 如果OSS中没有找到，尝试原来的API接口
    console.log('🔄 尝试调用后端种子详情API...');
    const response = await get(`/torrents/${id}`);
    return response;
  } catch (error) {
    console.warn('获取种子详情失败，回退到本地存储:', error);

    // 从localStorage获取种子详情
    const torrent = localGetTorrentById(id);

    if (!torrent) {
      throw new Error('种子不存在');
    }

    // 确保种子数据完整性，添加默认值
    const safeTorrent = {
      ...torrent,
      tags: torrent.tags || [],
      files: torrent.files || [],

      description: torrent.description || '暂无描述',
      coverImage: torrent.coverImage || 'https://via.placeholder.com/300x450'
    };

    return {
      success: true,
      data: {
        torrent: safeTorrent
      }
    };
  }
};

/**
 * 按分类获取种子
 * @param {string} category - 分类名称
 * @param {Object} params - 查询参数 (page, limit, sort, order)
 * @returns {Promise} - 分类下的种子列表
 */
export const getTorrentsByCategory = async (category, params = {}) => {
  try {
    // 构建查询字符串
    const query = new URLSearchParams();
    if (params.page) query.append('page', params.page);
    if (params.limit) query.append('limit', params.limit);
    if (params.sort) query.append('sort', params.sort);
    if (params.order) query.append('order', params.order);

    const queryString = query.toString();
    const endpoint = queryString ?
      `/torrents/category/${category}?${queryString}` :
      `/torrents/category/${category}`;

    const response = await get(endpoint);
    return response;
  } catch (error) {
    console.warn('按分类获取种子API连接失败，使用本地存储:', error);

    // 从localStorage获取分类种子
    const torrents = localGetTorrentsByCategory(category);

    // 简单的客户端分页
    const page = params.page || 1;
    const limit = params.limit || 20;
    const start = (page - 1) * limit;
    const end = start + limit;
    const paginatedTorrents = torrents.slice(start, end);

    return {
      success: true,
      data: {
        torrents: paginatedTorrents,
        pagination: {
          total: torrents.length,
          page: page,
          limit: limit,
          pages: Math.ceil(torrents.length / limit)
        }
      }
    };
  }
};

/**
 * 搜索种子
 * @param {string} query - 搜索关键词
 * @param {Object} params - 查询参数 (page, limit, category, tags)
 * @returns {Promise} - 搜索结果
 */
export const searchTorrents = async (query, params = {}) => {
  try {
    // 构建查询字符串
    const queryParams = new URLSearchParams();
    queryParams.append('query', query);
    if (params.page) queryParams.append('page', params.page);
    if (params.limit) queryParams.append('limit', params.limit);
    if (params.category) queryParams.append('category', params.category);
    if (params.tags) queryParams.append('tags', params.tags);

    const response = await get(`/torrents/search?${queryParams.toString()}`);
    return response;
  } catch (error) {
    console.warn('搜索种子API连接失败，使用本地存储:', error);

    // 从localStorage搜索种子
    const torrents = localSearchTorrents(query);

    // 如果有分类过滤
    let filteredTorrents = torrents;
    if (params.category) {
      filteredTorrents = filteredTorrents.filter(t => t.category === params.category);
    }

    // 如果有标签过滤
    if (params.tags) {
      const tagList = params.tags.split(',').map(tag => tag.trim());
      filteredTorrents = filteredTorrents.filter(t =>
        t.tags.some(tag => tagList.includes(tag))
      );
    }

    // 简单的客户端分页
    const page = params.page || 1;
    const limit = params.limit || 20;
    const start = (page - 1) * limit;
    const end = start + limit;
    const paginatedTorrents = filteredTorrents.slice(start, end);

    return {
      success: true,
      data: {
        torrents: paginatedTorrents,
        total: filteredTorrents.length,
        page: page,
        limit: limit
      }
    };
  }
};

/**
 * 上传种子
 * @param {FormData} formData - 包含种子文件和元数据的表单数据
 * @returns {Promise} - 上传结果
 */
export const uploadTorrent = async (formData) => {
  try {
    // 根据后端API调用/oss/upload_torrent接口
    const response = await uploadFile('/oss/upload_torrent', formData);

    console.log('📤 种子上传响应:', response);

    // 后端成功时返回 {torrent_url: "...", picture_url: "..."}
    // 失败时返回 {success: false, message: "..."}
    if (response.success === false) {
      // 明确的失败响应
      throw new Error(response.message || '上传种子失败');
    } else if (response.torrent_url || response.picture_url) {
      // 成功响应，包含URL
      return {
        success: true,
        message: '种子上传成功',
        data: {
          torrent_url: response.torrent_url,
          picture_url: response.picture_url,
          ...response
        }
      };
    } else {
      // 未知响应格式
      throw new Error('上传响应格式异常');
    }
  } catch (error) {
    console.warn('上传种子API连接失败，使用本地存储:', error);

    // 从formData中提取数据
    const name = formData.get('name');
    const classification = formData.get('classification');
    const torrentFile = formData.get('torrentFile');
    const pictureFile = formData.get('pictureFile');

    // 使用localStorage添加种子
    const result = localAddTorrent({
      title: name, // 使用title而不是name
      category: classification, // 显示用的分类字段
      classification: classification, // 保留原始分类字段用于筛选
      torrentFile: torrentFile ? URL.createObjectURL(torrentFile) : null,
      coverImage: pictureFile ? URL.createObjectURL(pictureFile) : 'https://via.placeholder.com/300x450',
      fileTimestamps: formData.get('fileTimestamps'),
      description: '用户上传的种子文件',
      tags: [],
      files: []
    });

    if (result.success) {
      return {
        success: true,
        message: '种子上传成功',
        data: {
          torrent: result.torrent
        }
      };
    } else {
      throw new Error(result.message || '上传种子失败');
    }
  }
};

/**
 * 下载种子
 * @param {string} torrentURL - 种子文件URL路径
 * @param {number|string} torrentId - 种子ID（必需，用于后端记录下载次数）
 * @returns {Promise} - 下载结果
 */
export const downloadTorrent = async (torrentURL, torrentId) => {
  try {
    // 验证必需参数
    if (!torrentId) {
      throw new Error('缺少种子ID参数，无法记录下载次数');
    }

    // 创建FormData对象，根据后端API要求
    const formData = new FormData();
    formData.append('torrentURL', torrentURL);
    formData.append('id', torrentId); // 新增：传递种子ID给后端

    // 使用fetch直接处理
    const token = localStorage.getItem('token');
    const response = await fetch('http://localhost:8080/oss/download_torrent', {
      method: 'POST',
      headers: token ? { 'Authorization': token } : {},
      body: formData
    });

    if (!response.ok) {
      throw new Error('下载失败');
    }

    // 获取响应头中的文件名
    const contentDisposition = response.headers.get('content-disposition');
    let filename = 'torrent.torrent';
    if (contentDisposition) {
      const filenameMatch = contentDisposition.match(/filename="?([^"]+)"?/);
      if (filenameMatch && filenameMatch[1]) {
        filename = filenameMatch[1];
      }
    }

    // 创建下载链接
    const blob = await response.blob();
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = filename;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);

    return {
      success: true,
      message: '下载成功，已记录下载次数'
    };
  } catch (error) {
    console.warn('下载种子API连接失败，使用本地存储:', error);

    // 使用localStorage下载种子
    // 从路径中提取ID，如果有的话
    let localTorrentId = torrentId;
    if (!localTorrentId && torrentURL) {
      const match = torrentURL.match(/\/([^\/]+)\.torrent$/);
      if (match && match[1]) {
        localTorrentId = match[1];
      }
    }

    const result = localDownloadTorrent(localTorrentId || 'default');

    if (result.success) {
      // 创建一个下载链接并模拟点击
      const link = document.createElement('a');
      link.href = result.torrentFileUrl;
      link.download = result.torrentName;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);

      return {
        success: true,
        message: '下载成功（本地模式）'
      };
    } else {
      throw new Error(result.message || '下载失败');
    }
  }
};



/**
 * 点赞种子
 * @param {number|string} torrentId - 种子ID
 * @returns {Promise} - 点赞结果
 */
export const likeTorrent = async (torrentId) => {
  try {
    const response = await post(`/torrents/${torrentId}/like`);
    return response;
  } catch (error) {
    console.warn('点赞种子API连接失败，使用本地存储:', error);

    const result = localLikeTorrent(torrentId);
    return {
      success: result.success,
      message: result.message,
      data: {
        liked: result.liked,
        likes: result.likes
      }
    };
  }
};

/**
 * 检查用户是否点赞了种子
 * @param {number|string} torrentId - 种子ID
 * @returns {Promise} - 点赞状态
 */
export const hasUserLikedTorrent = async (torrentId) => {
  try {
    const response = await get(`/torrents/${torrentId}/like-status`);
    return response;
  } catch (error) {
    console.warn('获取点赞状态API连接失败，使用本地存储:', error);

    const hasLiked = localHasUserLikedTorrent(torrentId);
    return {
      success: true,
      data: { hasLiked }
    };
  }
};

/**
 * 获取热门种子
 * @param {Object} params - 查询参数
 * @returns {Promise} - 热门种子列表
 */
export const getPopularTorrents = async (params = {}) => {
  try {
    const query = new URLSearchParams();
    if (params.limit) query.append('limit', params.limit);
    if (params.timeRange) query.append('timeRange', params.timeRange); // day, week, month

    const queryString = query.toString();
    const endpoint = queryString ? `/torrents/popular?${queryString}` : '/torrents/popular';

    const response = await get(endpoint);
    return response;
  } catch (error) {
    console.warn('获取热门种子API连接失败，使用本地存储:', error);

    const allTorrents = localGetAllTorrents();

    // 按点赞数和下载数排序
    const popularTorrents = allTorrents
      .sort((a, b) => {
        const scoreA = (a.likes || 0) * 2 + (a.downloads || 0);
        const scoreB = (b.likes || 0) * 2 + (b.downloads || 0);
        return scoreB - scoreA;
      })
      .slice(0, params.limit || 10);

    return {
      success: true,
      data: { torrents: popularTorrents }
    };
  }
};

/**
 * 增加种子浏览量
 * @param {number|string} torrentId - 种子ID
 * @returns {Promise} - 浏览量增加结果
 */
export const addWatch = async (torrentId) => {
  try {
    // 验证必需参数
    if (!torrentId) {
      throw new Error('缺少种子ID参数');
    }

    // 将字符串ID转换为整数，因为后端期望int类型
    const numericId = parseInt(torrentId, 10);
    if (isNaN(numericId)) {
      throw new Error('种子ID格式无效');
    }

    console.log('📈 准备增加浏览量，种子ID:', torrentId, '→', numericId);

    // 创建FormData对象，根据后端API要求
    const formData = new FormData();
    formData.append('id', numericId.toString()); // 确保发送的是有效的数字字符串

    // 使用fetch直接处理
    const token = localStorage.getItem('token');
    const response = await fetch('http://localhost:8080/oss/addWatch', {
      method: 'POST',
      headers: token ? { 'Authorization': token } : {},
      body: formData
    });

    if (!response.ok) {
      throw new Error('增加浏览量失败');
    }

    const result = await response.text(); // 后端返回 "OK" 字符串

    if (result === 'OK') {
      return {
        success: true,
        message: '浏览量已增加'
      };
    } else {
      throw new Error('增加浏览量失败');
    }
  } catch (error) {
    console.warn('增加浏览量API连接失败:', error);

    // 即使API失败，也不影响用户浏览体验，只是不记录浏览量
    return {
      success: false,
      message: '浏览量记录失败（不影响浏览）',
      error: error.message
    };
  }
};

export default {
  getAllUploadedTorrents,
  getTorrents,
  getTorrentDetail,
  getTorrentsByCategory,
  searchTorrents,
  uploadTorrent,
  downloadTorrent,

  likeTorrent,
  hasUserLikedTorrent,
  getPopularTorrents,
  addWatch
}; 